package com.clz.Dao.Impl;

import com.clz.Dao.UserDao;
import com.clz.entiy.User;
import com.clz.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Collections;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate = JDBCUtils.getJdbcTemplate();
    @Override
    public User selectUserByNameAndPsw(String username, String password) {
        String sql="select * from t_user where user_name=? and password = ?";
        List<User> list= jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),username,password);
        return list.isEmpty()?null:list.get(0);
    }

    @Override
    public User selectUserByName(String username) {
       String sql="select * from t_user where user_name=?";
        List<User> list= jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),username);
        return list.isEmpty()?null:list.get(0);
    }

    @Override
    public int insertUser(String username, String password) {
    String sql="insert into t_user(user_name,password) values (?,?)";
    return  jdbcTemplate.update(sql,username,password);
    }

    @Override
    public int selectUserCount() {
        String sql="SELECT count(user_id) FROM  t_user";
       return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public List<User> selectUserLimit(int startNumber, int pageSize,String keyword) {
        String sql="select * from t_user where user_name like concat('%',?,'%') order by user_id desc limit ?, ?";
        List<User> list =jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class),keyword,startNumber,pageSize);
        return list;
    }

    @Override
    public int deleteUserById(int userId) {
        String sql="delete from t_user where user_id=?";
        return jdbcTemplate.update(sql, userId);
    }

    @Override
    public int insertUser(User user) {
      String sql="insert into t_user(user_name,password,user_pic) values (?,?,?)";
      return jdbcTemplate.update(sql,user.getUserName(),user.getPassword(),user.getUserPic());
    }

    @Override
    public User selectUserById(int userId) {
        String sql ="select * from t_user where user_id =?";
        List<User> list =jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), userId);
        return list.isEmpty()?null:list.get(0);
    }
}
